﻿using Microsoft.AspNetCore.Components;
using System.Net.Http.Json;

namespace FastapiBlazorBlog.Pages
{
    public class CategoryBase : ComponentBase
    {
        [Inject]
        public HttpClient Http { get; set; }

        /// <summary>
        /// 接收id路径参数
        /// </summary>
        [Parameter]
        public int Id { get; set; }



        public class RespData<T>
        {
            public int Code { get; set; }
            public string Msg { get; set; }
            public List<T> Data { get; set; } = new List<T>();
        }

        public class Category
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
        public class CategoryDto
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }

        public class ArticleDto
        {
            public int Id { get; set; }
            public string Title { get; set; }
            public string Description { get; set; }
            public string Content { get; set; }
            public int Created_at { get; set; }
            public int Updated_at { get; set; }
            public Category Category { get; set; }
        }

        /// <summary>
        /// 接收后端响应的文章列表数据
        /// </summary>
        public List<ArticleDto> articles = new List<ArticleDto>();

        /// <summary>
        /// 接收后端响应的分类列表数据
        /// </summary>
        public List<CategoryDto> categories = new List<CategoryDto>();


        /// <summary>
        /// 生命周期：设置参数之后调用
        /// 在 OnInitialized 或 OnInitializedAsync 中初始化组件后
        /// </summary>
        /// <returns></returns>
        protected override async Task OnParametersSetAsync()
        {
            var cateRes = await Http.GetFromJsonAsync<RespData<CategoryDto>>("/api/categories");
            categories = cateRes.Data;

            var artRes = await Http.GetFromJsonAsync<RespData<ArticleDto>>($"/api/category/{Id}/artlist");
            articles = artRes.Data;
            await base.OnParametersSetAsync();
        }
    }
}
